package com.jz.netthings.application.bodyCheck.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jz.netthings.appengine.baseData.ProviderData;
import com.jz.netthings.appengine.baseData.ProviderInfo;
import com.jz.netthings.appengine.mapper.ProviderDataMapper;
import com.jz.netthings.appengine.mapper.ProviderInfoMapper;
import com.jz.netthings.appengine.queue.MachineMgr;
import com.jz.netthings.appengine.queue.ProviderQueue;
import com.jz.netthings.appengine.support.BeanSupport;
import com.jz.netthings.application.bodyCheck.bean.BodyCheck;
import com.jz.netthings.application.bodyCheck.bean.BodyCheckInfo;
import com.jz.netthings.application.bodyCheck.bean.BodyCheckStatus;
import com.jz.netthings.application.bodyCheck.bean.MyPage;
import com.jz.netthings.application.bodyCheck.mapper.mysql.BodyCheckMapper;
import com.jz.netthings.application.bodyCheck.service.BodyCheckService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.jz.netthings.application.heatseal.bean.HeatSeal;
import com.jz.netthings.application.providerCollection.bean.ProviderCollection;
import com.jz.netthings.application.providerCollection.mapper.mysql.ProviderCollectionMapper;
import com.jz.netthings.application.providerCreate.bean.ProviderXp;
import com.jz.netthings.application.providerCreate.mapper.mysql.ProviderXpMapper;
import com.jz.netthings.application.utils.AppUtils;
import com.jz.netthings.bean.system.JyUser;
import com.jz.netthings.exception.AdscmSystemException;
import com.jz.netthings.system.mapper.mysql.JyUserMapper;
import com.jz.netthings.utils.AdscmBaseUtils;
import com.jz.netthings.utils.AdscmDateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;


/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author lzf
 * @since 2019-02-26
 */
@Slf4j
@Service
public class BodyCheckServiceImpl extends ServiceImpl<BodyCheckMapper, BodyCheck> implements BodyCheckService {
    @Autowired
    private BodyCheckMapper bodyCheckMapper;
    @Autowired
    private JyUserMapper jyUserMapper;
    @Autowired
    private   ProviderXpMapper providerXpMapper;
    @Autowired
    private ProviderCollectionMapper providerCollectionMapper;
    @Autowired
    private ProviderDataMapper providerDataMapper;
    @Autowired
    private ProviderInfoMapper providerInfoMapper;
    @Autowired
    ProviderQueue providerQueue;
    @Value("${ly.upload.baseUrl}")
    String photoUrl;
    /**
     * engine模块的IP和端口
     */
    @Value("${netty.engine.ipAddress}")
    private String engineIp;
    @Value("${netty.engine.serverPort}")
    private String engineServerPort;

    /**
     * 查询体检信息
     * @param recodeCreateTime
     * @param bigCreateTime
     * @param lessCreateTime
     * @return
     */
    @Override
    public MyPage<BodyCheck> queryByTime(String recodeCreateTime, String bigCreateTime, String lessCreateTime, String cardid, String name, Integer pageSize, Integer currentPage) throws  AdscmSystemException{
        if (currentPage!=0){
            if (currentPage==1){
                currentPage=0;
            }else {
                currentPage=((currentPage-1)*pageSize)/*-1*/;
            }
        }

        MyPage<BodyCheck> myPage=new MyPage<>();

        List<ProviderInfo> info = null;
        Wrapper<ProviderInfo> wrapper = null;
        List<Long> infoIds = new ArrayList<>();

        if (AdscmBaseUtils.getInstance().isNotEmpty(name,null)){
            wrapper = new EntityWrapper<>();
            wrapper.like("name",name);
            recodeCreateTime = null;
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(cardid,null)){
            if(wrapper == null){
                wrapper = new EntityWrapper<>();
            }
            wrapper.eq("cardId",cardid);
            recodeCreateTime = null;
        }
        if (wrapper != null){
            info = providerInfoMapper.selectList(wrapper);
            for (ProviderInfo providerInfo : info) {
                infoIds.add(providerInfo.getId());
            }
        }

        Integer count = bodyCheckMapper.queryCount(recodeCreateTime, bigCreateTime, lessCreateTime, infoIds);
        List<BodyCheck> list = bodyCheckMapper.queryByTime(currentPage, pageSize, recodeCreateTime, bigCreateTime, lessCreateTime, infoIds);

        for (BodyCheck bodyCheck : list) {
            if (AdscmBaseUtils.getInstance().isNotEmpty(bodyCheck.getProviderNo(),null)){
                bodyCheck.setCardId(providerInfoMapper.selectById(bodyCheck.getProviderNo()).getCardId());
            }
            //根据id查询，医生名
            if (null!=bodyCheck.getBodyCheckWorker()){
                JyUser jyUser = jyUserMapper.selectById(bodyCheck.getBodyCheckWorker());
                if (jyUser != null){
                    bodyCheck.setBodyCheckWorkerName(jyUser.getName());
                }
            }
            if (null!=bodyCheck.getCreateNurse()){
                JyUser jyUser = jyUserMapper.selectById(bodyCheck.getCreateNurse());
                if (jyUser != null){
                    bodyCheck.setCreateNurseName(jyUser.getName());
                }
            }

        }
        myPage.setItems(list);
        myPage.setTotal(count);
        return myPage;
    }

    /**
     * 修改体检表
     * @param bodyCheck
     * @return
     */
    @Override
    @Transactional
    public Integer updateByBodyCheckNo(BodyCheck bodyCheck) throws AdscmSystemException{
        SimpleDateFormat dateFormat =new SimpleDateFormat("yyyy-MM-dd HH:ss:mm");
        SimpleDateFormat dateFormat1 =new SimpleDateFormat("yyyy-MM-dd");
        if (AdscmBaseUtils.getInstance().isNotEmpty(bodyCheck.getBodyCheckResult(),null)){
            bodyCheck.setBodyEndTime(dateFormat.format(new Date()));
            bodyCheck.setRecodeEndTime(dateFormat.format(new Date()));
        }
        if (AdscmBaseUtils.getInstance().isNotEmpty(bodyCheck.getBodyCheckResult(),null)){
            bodyCheck.setMODIFY_TIME(dateFormat.format(new Date()));
            bodyCheck.setSYNDATE(dateFormat1.format(new Date()));
            bodyCheck.setRecodeStatus(1);
        }

        Integer result = bodyCheckMapper.updateById(bodyCheck);

        if (bodyCheck.getBodyCheckResult() != null && AdscmBaseUtils.getInstance().isNotEmpty(bodyCheck.getBodyEndTime(), null)) {
            //修改缓存，发送消息给分配客户端
            ProviderData providerData = new ProviderData();
            providerData.setProviderId(Long.parseLong(bodyCheck.getProviderNo()));

            providerData = providerQueue.selectProviderData(providerData);
            //这两个不为null，才表示体检结束了
            providerData.setBodyCheckId(bodyCheck.getBodyRecodeId());
            providerData.setBodyCheckNo(bodyCheck.getBodyCheckNo());
            boolean bodyIsPass = false;
            if (bodyCheck.getBodyCheckResult() == 1) {
                bodyIsPass = true;
            }
            providerData.setBodyIsPass(bodyIsPass);
            providerData.setBodyCheckPassTime(AdscmDateUtils.parseDate(bodyCheck.getBodyEndTime()));
            providerQueue.updateProviderData(providerData);

//            MachineMgr.getInstance().sendMsgToAllotCtxs(BeanSupport.loadToAllotMsg(providerData, null));

            AppUtils.sendMsgToAllotCtxs(providerData,"http://"+engineIp+":"+engineServerPort);
        } else {
            throw new AdscmSystemException("体检记录还未处理，不能进行【完成体检】操作");
        }


        return result;
    }

    /**
     * 根据id查询医生或者护士（id=3护士角色、id=4医生角色）
     * @param id
     * @return
     */
    @Override
    public List<JyUser> queryDoctor(String id) {
        return jyUserMapper.queryUsersByRoleId(id);
    }

    /**
     * 根据类型查询体检状态（type=1五官、胸部等是否正常type=2拒绝原因）
     * @param type
     * @return
     */
    @Override
    public List<BodyCheckStatus> bodyCheckStatus(String type) {
        return bodyCheckMapper.queryBodyCheckStatus(type);
    }

    @Override
    public BodyCheckInfo BODY_CHECK_INFOS(String id) throws AdscmSystemException {

        BodyCheckInfo bodyCheckInfo = bodyCheckMapper.queryBodyCheckInfo(id);
        if (bodyCheckInfo==null){
            throw new AdscmSystemException("没有查询到该浆员的建档信息");
        }else {
            bodyCheckInfo.setPhoto(photoUrl+bodyCheckInfo.getPhoto());
            return bodyCheckInfo;
        }
    }

    @Override
    public List<BodyCheck> queryByName(String name,String bigCreateTime,String lessCreateTime) {
        List<BodyCheck> list=bodyCheckMapper.queryByName(name,"'"+bigCreateTime+"'",
                "'"+lessCreateTime+"'");
        for (BodyCheck bodyCheck : list) {

            if (null!=bodyCheck.getBodyCheckWorker()){
                bodyCheck.setBodyCheckWorkerName(jyUserMapper.selectById(bodyCheck.getBodyCheckWorker()).getName());
            }
            if (null!=bodyCheck.getCreateNurse()){
                bodyCheck.setCreateNurseName(jyUserMapper.selectById(bodyCheck.getCreateNurse()).getName());
            }
            if (null!=bodyCheck.getProviderNo()){
                bodyCheck.setProviderNoName(bodyCheckMapper.queryBodyCheckInfo(String.valueOf(bodyCheck.getProviderNo())).getName());
            }
        }
        return bodyCheckMapper.queryByName(name,bigCreateTime,lessCreateTime);
    }

    /**
     *根据providerNO查看 该浆员是否需要大体检和查看浆员的基本信息
     * @param id
     * @return
     */
    @Override
    public List<BodyCheckInfo> queryByBigCheck(String id) throws AdscmSystemException {
//        List<BodyCheckInfo> bodyCheckInfos = bodyCheckMapper.queryByBigCheck(id);
//        if (AdscmBaseUtils.getInstance().isNotEmpty(bodyCheckInfos,null)&&bodyCheckInfos.size()>0){
//            if (AdscmBaseUtils.getInstance().isNotEmpty(bodyCheckInfos.get(0).getValidDate(),null)){
//                int diffDays = AdscmDateUtils.daysBetween(new Date(), bodyCheckInfos.get(0).getValidDate());
//                if (diffDays>30){
//                    bodyCheckInfos.get(0).setIsOrNotXP(true);
//                }
//            }else {
//                bodyCheckInfos.get(0).setIsOrNotXP(false);
//                throw new AdscmSystemException("献浆员没有历史胸片信息");
//            }
//        }else {
//            throw new AdscmSystemException("该卡号无匹配信息");
//        }
        return null;
    }
}
